import { PlusOutlined } from '@ant-design/icons';
import type { TableColumnsType } from 'antd';
import { Button, Form, Input, message, Space, Table, Typography } from 'antd';
import { useEffect, useState } from 'react';
import { v4 } from 'uuid';

import hooks from '../../../hooks';
import EditableCell from './EditableCell';

import type { IBtnItem } from '@/types/systemManagement/menu';
import { DisableTypeEnum } from '@/types/systemManagement/menu';

const FunctionAccessField = () => {
  const [editType, setEditType] = useState<'new' | 'edit'>();
  const [tableForm] = Form.useForm<IBtnItem>();
  const [btnList, setBtnList] = useState<IBtnItem[]>([]);

  const { form, editFunctionAccessKey, setEditFunctionAccessKey } = hooks.useContainer();

  const handleRowAdd = () => {
    if (!!editFunctionAccessKey) {
      message.error('请先操作正在编辑的行');
      return;
    }
    const uuid = v4();
    setBtnList([
      ...btnList,
      {
        key: uuid,
        menuName: '',
        menuCode: '',
        disableType: '',
      },
    ]);

    tableForm.setFieldsValue({ key: uuid });
    setEditFunctionAccessKey(uuid);
  };

  const handleRowSave = async () => {
    try {
      const record = await tableForm.validateFields();
      const newData = [...btnList];
      const index = newData.findIndex((item) => item.key === editFunctionAccessKey);
      if (index > -1) {
        newData.splice(index, 1, {
          ...newData[index],
          ...record,
        });
        setBtnList(newData);
        setEditFunctionAccessKey(undefined);
      } else {
        newData.push({ ...record });
        setBtnList(newData);
        setEditFunctionAccessKey(undefined);
      }
      tableForm.resetFields();
    } catch (err) {
      console.error(err);
    }
  };

  const handleRowDelete = (key: string | number) => {
    setBtnList(btnList.filter((item) => item.key !== key));
  };

  const handleRowEdit = (record: IBtnItem) => {
    tableForm.setFieldsValue({
      menuName: record?.menuName,
      disableType: record?.disableType,
      id: record?.id,
      menuCode: record?.menuCode,
      key: record?.key,
    });
    setEditFunctionAccessKey(record?.key);
  };

  const handleRowCancel = () => {
    setEditFunctionAccessKey(undefined);
    tableForm.resetFields();
    if (editType === 'new' && !!editFunctionAccessKey) {
      handleRowDelete(editFunctionAccessKey);
    }
  };

  const columns: TableColumnsType<IBtnItem> = [
    {
      width: '26%',
      title: '名称',
      dataIndex: 'menuName',
      onCell: (record) => ({
        dataIndex: 'menuName',
        title: '名称',
        editing: record?.key === editFunctionAccessKey,
      }),
    },
    {
      width: '34%',
      title: '权限标识',
      dataIndex: 'menuCode',
      ellipsis: true,
      onCell: (record) => ({
        title: '权限标识',
        dataIndex: 'menuCode',
        editing: record?.key === editFunctionAccessKey,
      }),
    },
    {
      width: '20%',
      title: '受限处理机制',
      dataIndex: 'disableType',
      onCell: (record) => ({
        title: '受限处理机制',
        dataIndex: 'disableType',
        editing: record?.key === editFunctionAccessKey,
        type: 'select',
        options: [
          {
            label: '置灰',
            value: DisableTypeEnum.ASH,
          },
          {
            label: '不展示',
            value: DisableTypeEnum.DIS,
          },
        ],
      }),
    },
    {
      width: '20%',
      title: '操作',
      align: 'right',
      key: 'access-operation',
      render: (_, record) => {
        return record?.key === editFunctionAccessKey ? (
          <Space>
            <Typography.Link
              onClick={() => {
                handleRowSave();
              }}
            >
              保存
            </Typography.Link>
            <Typography.Link
              onClick={() => {
                handleRowCancel();
              }}
            >
              取消
            </Typography.Link>
          </Space>
        ) : (
          <Space>
            <Typography.Link
              // 有 editKey 的时候才会禁用（防止误点击）
              disabled={!!editFunctionAccessKey}
              onClick={() => {
                setEditType('edit');
                handleRowEdit(record);
              }}
            >
              编辑
            </Typography.Link>
            <Typography.Link
              type="danger"
              // 有 editKey 的时候才会禁用（防止误点击）
              disabled={!!editFunctionAccessKey}
              onClick={() => {
                handleRowDelete(record?.key);
              }}
            >
              删除
            </Typography.Link>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    setBtnList(
      form.getFieldValue('btnList')?.map((item: IBtnItem) => ({
        ...item,
        key: item?.id,
      })) || [],
    );
  }, []);

  useEffect(() => {
    form.setFieldsValue({
      btnList: btnList?.map((item) => ({
        id: item?.id,
        menuCode: item?.menuCode,
        menuName: item?.menuName,
        disableType: item?.disableType,
      })),
    });
  }, [btnList]);

  return (
    <>
      <Button
        icon={<PlusOutlined />}
        onClick={() => {
          setEditType('new');
          handleRowAdd();
        }}
        style={{ marginBottom: 10, float: 'right' }}
      >
        新增功能权限
      </Button>
      <Form
        form={tableForm}
        component={false}
        onFinish={(values) => {
          console.log(values);
        }}
      >
        <Form.Item name="id" hidden>
          <Input />
        </Form.Item>
        <Table
          rowKey="id"
          dataSource={btnList}
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          columns={columns}
          pagination={false}
        />
      </Form>
    </>
  );
};

export default FunctionAccessField;
